package cn.com.hori.cms.service.impl;

import cn.com.hori.cms.dao.ColumnRepository;
import cn.com.hori.cms.dao.ContentRepository;
import cn.com.hori.cms.entities.ColumnAdmin;
import cn.com.hori.cms.entities.ContentPublish;
import cn.com.hori.cms.model.ColumnAndContent;
import cn.com.hori.cms.service.UserShowService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.LinkedList;
import java.util.List;

/**
 * @author 刘艺
 * @date 2018/3/14 17:30
 */
@Service
public class UserShowServiceImpl implements UserShowService {

    @Autowired
    private ColumnRepository columnRepository;

    @Autowired
    private ContentRepository contentRepository;

    /**
     * 得到所有的栏目和文章
     *
     * @return
     */
    @Override
    public List<ColumnAndContent> getAllColumn() {
        List<ColumnAndContent> columnAndContents = new LinkedList<>();

        List<ColumnAdmin> columnList = columnRepository.findAll();
        columnList.forEach(columnAdmin -> {
            List<ContentPublish> contents = contentRepository.findAllByColumnId(columnAdmin.getColumnId());
            if (contents != null && contents.size() > 0) {
                ColumnAndContent columnAndContent = new ColumnAndContent();
                columnAndContent.setColumnId(columnAdmin.getColumnId());
                columnAndContent.setColumnName(columnAdmin.getColumnName());

                // 控制每个栏目下只放置5个最新的文章
                int maxLength = 5;
                if (contents.size() < 5){
                    maxLength = contents.size();
                }
                for (int i =0; i < maxLength; i++){
                    columnAndContent.getContentPublishes().add(contents.get(i));
                }
                columnAndContents.add(columnAndContent);
            }
        });
        return columnAndContents;
    }


    /**
     * 得到某一个栏目下的所有文章
     *
     * @param columnId 指定的栏目 Id
     * @return 返回指定的栏目下的所有文章的
     */
    @Override
    public ColumnAndContent getContentList(String columnId) {
        ColumnAndContent columnAndContent = new ColumnAndContent();
        ColumnAdmin columnAdmin = columnRepository.getOneBycolumnId(columnId);
        List<ContentPublish> contents = contentRepository.findAllByColumnId(columnId);

        columnAndContent.setColumnId(columnId);
        columnAndContent.setColumnName(columnAdmin.getColumnName());
        columnAndContent.setContentPublishes(contents);
        return columnAndContent;
    }

    /**
     * 根据 contentId 获得指定的文章实体
     *
     * @param contentId 指定的 文章ID
     * @return 返回文章实体
     */
    @Override
    public ContentPublish getContent(String contentId) {
        ContentPublish contentPublish = contentRepository.findByContentId(contentId);
        return contentPublish;
    }
}
